package cn.edu.zjicm.wordsnet_d.synchronize;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import cn.edu.zjicm.wordsnet_d.data.BoardItem;
import cn.edu.zjicm.wordsnet_d.data.BoardList;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.download.JudgeNetwork;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import android.content.Context;
import android.os.Handler;

public class LeaderBoardInterface extends ServerInterface {

	public static final int PUNCH_BOARD = 1;
	public static final int EXP_BOARD = 2;

	private static LeaderBoardInterface mInstance;

	public static LeaderBoardInterface getInstance(Context context) {
		if (mInstance == null) {
			mInstance = new LeaderBoardInterface(context);
		}
		return mInstance;
	}

	private LeaderBoardInterface(Context context) {
		super(context);
	}

	public void getUserBoard(int type, Handler handler) {
		if (JudgeNetwork.getInstance(context).isWifiConnected() || JudgeNetwork.getInstance(context).isMobileConnected()) {
			new GetUserBoardThread(type, handler).start();
		} else {
			// Toast.makeText(context, "请确认网络是否连接", Toast.LENGTH_LONG).show();
			handler.sendMessage(handler.obtainMessage(UserInterface.MSG_BAD_NETWORK));
		}
	}

	public class GetUserBoardThread extends Thread {
		int type;
		String token;
		Handler handler;

		public GetUserBoardThread(int type, Handler handler) {
			this.type = type;
			this.token = AppPreference.getToken(context);
			this.handler = handler;
		}

		@Override
		public void run() {
			DefaultHttpClient client = new DefaultHttpClient();
			UserInterface.setClientTimeout(client);

			List<NameValuePair> list = new ArrayList<NameValuePair>();
			NameValuePair pair1 = new BasicNameValuePair("t", token);
			list.add(pair1);

			String url = null;
			if (type == PUNCH_BOARD)
				url = GET_PUNCH_BOARD;
			else if (type == EXP_BOARD)
				url = GET_EXP_BOARD;

			long start = System.currentTimeMillis();
			try {
				HttpEntity entity = new UrlEncodedFormEntity(list);
				HttpPost post = new HttpPost(url);
				post.setEntity(entity);
				HttpResponse response = client.execute(post);

				if (response.getStatusLine().getStatusCode() == 200) {
					String str = EntityUtils.toString(response.getEntity(), "utf-8");
					JSONObject result = new JSONObject(str);
					String message = result.getString("message");
					boolean success = result.getBoolean("success");

					if (success) {
						JSONArray data = result.getJSONArray("board");
						List<BoardItem> boardItemList = new ArrayList<BoardItem>();
						for (int i = 0; i < data.length(); i++) {
							String temp = data.getString(i);
							int index = temp.lastIndexOf(':');
							boardItemList.add(new BoardItem(temp.substring(0, index), Integer.parseInt(temp.substring(index + 1))));
						}
						Collections.sort(boardItemList);
						BoardItem myData = null;
						BoardList boradList;
						for (int i = 0; i < boardItemList.size(); i++) {
							boardItemList.get(i).setRank(i + 1);
							if (boardItemList.get(i).getElement().equals(AppPreference.getNickName(context))) {
								myData = boardItemList.get(i);
							}
						}

						if (myData != null) {
							boardItemList.add(0, myData);
							boradList = new BoardList(boardItemList, true, myData.getRank());
						} else {
							boradList = new BoardList(boardItemList, false, 0);
						}
						handler.sendMessage(handler.obtainMessage(UserInterface.MSG_SUCCESS, boradList));
					} else {
						handler.sendMessage(handler.obtainMessage(UserInterface.MSG_UNSUCCESS));
					}
				} else {
					handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
				}
			} catch (Exception e) {
				e.printStackTrace();
				handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
			}
		}
	}

	public void getSchoolBoard(Handler handler) {
		if (JudgeNetwork.getInstance(context).isWifiConnected() || JudgeNetwork.getInstance(context).isMobileConnected()) {
			new GetSchoolBoardThread(handler).start();
		} else {
			// Toast.makeText(context, "请确认网络是否连接", Toast.LENGTH_LONG).show();
			handler.sendMessage(handler.obtainMessage(UserInterface.MSG_BAD_NETWORK));
		}
	}

	public class GetSchoolBoardThread extends Thread {
		String token;
		Handler handler;

		public GetSchoolBoardThread(Handler handler) {
			this.token = AppPreference.getToken(context);
			this.handler = handler;
		}

		@Override
		public void run() {
			DefaultHttpClient client = new DefaultHttpClient();
			UserInterface.setClientTimeout(client);

			List<NameValuePair> list = new ArrayList<NameValuePair>();
			NameValuePair pair1 = new BasicNameValuePair("t", token);
			list.add(pair1);

			try {
				HttpEntity entity = new UrlEncodedFormEntity(list);
				HttpPost post = new HttpPost(GET_SCHOOL_BOARD);
				post.setEntity(entity);
				HttpResponse response = client.execute(post);

				if (response.getStatusLine().getStatusCode() == 200) {
					String str = EntityUtils.toString(response.getEntity(), "utf-8");
					JSONObject result = new JSONObject(str);
					String message = result.getString("message");
					boolean success = result.getBoolean("success");

					if (success) {
						String myschool = result.getString("myschool");
						String top10 = result.getString("top10");
						Gson gson = new Gson();
						List<BoardItem> top10List = gson.fromJson(top10, new TypeToken<List<BoardItem>>() {
						}.getType());
						createTopTenRank(top10List);
						// if(result.getString("myschoolrank") != "null" &&
						// result.getString("near10") != "null"){
						int myschoolrank = 0;
						if (!result.isNull("myschoolrank") && !result.isNull("near10")) {
							myschoolrank = result.getInt("myschoolrank") + 1;
							String near10 = result.getString("near10");
							List<BoardItem> near10List = gson.fromJson(near10, new TypeToken<List<BoardItem>>() {
							}.getType());
							top10List = MergerList(top10List, near10List, myschool, myschoolrank);
						}

						BoardItem myData = null;
						BoardList boradList;
						for (int i = 0; i < top10List.size(); i++) {
							if (top10List.get(i).getElement().equals(AppPreference.getSchoolName(context))
									&& top10List.get(i).getRank() == myschoolrank) {
								myData = top10List.get(i);
							}
						}
						if (myData != null) {
							top10List.add(0, myData);
							boradList = new BoardList(top10List, true, myData.getRank());
						} else {
							boradList = new BoardList(top10List, false, 0);
						}
						handler.sendMessage(handler.obtainMessage(UserInterface.MSG_SUCCESS, boradList));
					} else {
						handler.sendMessage(handler.obtainMessage(UserInterface.MSG_UNSUCCESS));
					}
				} else {
					handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
				}
			} catch (Exception e) {
				e.printStackTrace();
				handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
			}
		}
	}

	public void createTopTenRank(List<BoardItem> top10List) {
		for (int i = 0; i < top10List.size(); i++)
			top10List.get(i).setRank(i + 1);
	}

	public List<BoardItem> MergerList(List<BoardItem> top10List, List<BoardItem> near10List, String myschool, int myschoolrank) {
		int i, j;
		for (i = 0; i < near10List.size(); i++)
			if (near10List.get(i).getElement().equals(myschool)) {
				near10List.get(i).setRank(myschoolrank);
				break;
			}
		for (j = i - 1; j >= 0; j--)
			near10List.get(j).setRank(myschoolrank + j - i);
		for (j = i + 1; j < near10List.size(); j++)
			near10List.get(j).setRank(myschoolrank + j - i);
		top10List.addAll(near10List);
		Collections.sort(top10List);
		for (i = top10List.size() - 1; i > 0; i--) {
			if (top10List.get(i).getElement().equals(top10List.get(i - 1).getElement()))
				top10List.remove(i);
		}
		return top10List;
	}

}
